package org.jizp.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jizp.web.bean.ResultBean;
import org.jizp.web.bean.XmlBean;
import org.jizp.web.utils.StringUtils;
import org.jizp.web.utils.XmlParseUtil;

public class DispatcherActionServlet extends HttpServlet {
	private static final String CONTEXTCONFIGLOCATION = "contextConfigLocation";
	private static final String CLASSPATH = "/WEB-INF/classes/";

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Constructor of the object.
	 */
	public DispatcherActionServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String uri = request.getRequestURI();
		//请求的Java类
		String actionClassName = uri.substring(uri.lastIndexOf("/") + 1, uri.lastIndexOf("."));
		
		//请求的是类的哪个方法
		Enumeration<String> requestMethod = request.getParameterNames();
		String requestMethodName = requestMethod.nextElement();	
		if(requestMethodName != null && !"".equals(requestMethodName)){
			StringBuilder forwardUrl = new StringBuilder();
			try {
				Map<String, XmlBean> mvcMapping = (Map<String, XmlBean>) this.getServletContext().getAttribute(XmlParseUtil.MVCMAPPING);
				XmlBean xmlBean = mvcMapping.get(actionClassName);
				String actionClassType = xmlBean.getClassType();
				if(StringUtils.isNotEmpty(actionClassType)){
					Class clazz = Class.forName(actionClassType);
					Object actionClass = clazz.newInstance();
					Method[] methods = clazz.getDeclaredMethods();
					String forward = "";
					for(Method method : methods){
						if(requestMethodName.equals(method.getName())){
							forward =  String.valueOf(method.invoke(actionClass, request, response));
							break;
						}
					}
					
					if(StringUtils.isNotEmpty(forward)){
						for(ResultBean resultBean : xmlBean.getResultBeans()){
							if(forward.equalsIgnoreCase(resultBean.getName())){
								forwardUrl.append(resultBean.getPrefix())
											.append(forward)
											.append(resultBean.getSuffix());
								break;
							}
						}
					}
				}else{
					throw new Exception(actionClassName + " is not class ");
				}
			} catch (Exception e) {
				e.printStackTrace();
				PrintWriter printWriter = response.getWriter();
				printWriter.write(e.getMessage());
				printWriter.flush();
				printWriter.close();
			}
			request.getRequestDispatcher(forwardUrl.toString()).forward(request, response);
		}
		
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		String xmlPath = this.getServletConfig().getInitParameter(this.CONTEXTCONFIGLOCATION);
		if(StringUtils.isNotEmpty(xmlPath) && (xmlPath.indexOf("classpath:") == 0)){
			xmlPath = xmlPath.replace("classpath:", this.CLASSPATH);
		}else{
			xmlPath = "/WEB-INF/"+this.getServletConfig().getServletName()+"-servlet.xml";
		}
		XmlParseUtil.parseXml(xmlPath, this.getServletContext());
		System.out.println(xmlPath);
	}

}
